package com.jsmy.marketing.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jsmy.marketing.R;
import com.jsmy.marketing.adapter.ComFragmentAdapter;
import com.jsmy.marketing.adapter.DailyDialogAdapter;
import com.jsmy.marketing.adapter.FzAdapter;
import com.jsmy.marketing.api.RetrofitManager;
import com.jsmy.marketing.base.BaseActivity;
import com.jsmy.marketing.bean.AppZLGroupBean;
import com.jsmy.marketing.bean.BaseBean;
import com.jsmy.marketing.bean.CustomerBean;
import com.jsmy.marketing.bean.GTKJListBean;
import com.jsmy.marketing.bean.GtrzLxBean;
import com.jsmy.marketing.bean.NewsBean;
import com.jsmy.marketing.common.Link;
import com.jsmy.marketing.fg.BaseFragment;
import com.jsmy.marketing.fg.CustomerDailyFragment;
import com.jsmy.marketing.fg.CustomerListenerFragment;
import com.jsmy.marketing.fg.CustomerPlantFragment;
import com.jsmy.marketing.fg.CustomerResourceFragment;
import com.jsmy.marketing.manager.UserManager;
import com.jsmy.marketing.utils.MesssageUtil;
import com.jsmy.marketing.utils.NetWork;
import com.jsmy.marketing.utils.ToastUtil;
import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class CustomerActivity extends BaseActivity {


    @BindView(R.id.img_avatar)
    ImageView imgAvatar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_group)
    TextView tvGroup;
    @BindView(R.id.tv_product)
    TextView tvProduct;
    @BindView(R.id.tv_stage)
    TextView tvStage;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_email)
    TextView tvEmail;
    @BindView(R.id.tv_wechat)
    TextView tvWechat;
    @BindView(R.id.tv_tecen)
    TextView tvTecen;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.m_tab)
    TabLayout mTab;
    @BindView(R.id.m_viewpage)
    ViewPager mViewpage;
    ComFragmentAdapter adapter;
    List<Fragment> fragments;
    List<String> list;
    @BindView(R.id.nest_view)
    NestedScrollView nestView;
    public String kid;

    List<GTKJListBean.DataBean.ListBean> kjList;
    List<GtrzLxBean.DataBean.ListBean> mGtrzlxList;

    private ClipboardManager cm;
    CustomerPlantFragment customerPlantFragment;
    CustomerListenerFragment customerListenerFragment;
    CustomerDailyFragment customerDailyFragment;
    CustomerResourceFragment customerResourceFragment;

    @Override
    protected int resId() {
        return R.layout.activity_customer;
    }

    BaseFragment fragment;

    @Override
    protected void initData() {
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomerActivity.this.finish();
            }
        });
        nestView.setFillViewport(true);
        list = new ArrayList<>();
        list.add("沟通计划");
        list.add("沟通日志");
        list.add("已发资料");
        customerPlantFragment = new CustomerPlantFragment();
        customerListenerFragment = new CustomerListenerFragment();
        customerDailyFragment = new CustomerDailyFragment();
        customerResourceFragment = new CustomerResourceFragment();
        mTab.setTabMode(TabLayout.MODE_FIXED);
        adapter = new ComFragmentAdapter(getSupportFragmentManager(), new String[]{"沟通计划", "试听列表", "沟通日志", "已发资料"}) {


            @Override
            public Fragment getItem(int postion) {
                switch (postion) {
                    case 0:
                        fragment = customerPlantFragment;
                        break;
                    case 1:
                        fragment = customerListenerFragment;
                        break;
                    case 2:
                        fragment = customerDailyFragment;
                        break;
                    case 3:
                        fragment = customerResourceFragment;
                        break;
                }
                return fragment;
            }
        };
        mViewpage.setAdapter(adapter);
        mViewpage.setOffscreenPageLimit(3);
        mTab.setupWithViewPager(mViewpage);
        cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        kid = getPrevIntent().getStringExtra("kid");
        getkhzlinfo(kid);
        getgtkjlist();
        getgtrzlxlist();
    }

    private NewsBean newsBean;

    @Override
    public void refreshData(Object object, String api_id) {
        switch (api_id) {
            case Link.APP_ZILIAO_choose:
                newsBean = (NewsBean) object;
                break;
            case Link.APP_KHZL_INFO:
                CustomerBean.DataBean bean = ((CustomerBean) object).getData();
                setCustomerInfo(bean);
                break;
            case Link.APP_GTKJ_LIST:
                kjList = ((GTKJListBean) object).getData().getList();
                break;
            case Link.APP_GTLX:
                mGtrzlxList = ((GtrzLxBean) object).getData().getList();
                break;
            case Link.APP_SAVE_NEW_GTRZ_INFO:
                ToastUtil.showShort(this, "保存成功！");
                customerDailyFragment.update();
                break;
            case Link.APP_SAVE_GTPLAN_INFO:
                ToastUtil.showShort(this, "保存成功！");
                customerPlantFragment.update();
                break;
            case Link.APP_UPDATEFZ://分组数据
                BaseBean baseBean = (BaseBean) object;
                if (baseBean.getCode().equals("Y")) {
                    ToastUtil.showShort(this, "修改成功！");
                } else {
                    ToastUtil.showShort(this, "修改失败！");
                }
                break;
            case Link.APP_ZL_GROUP_LIST:
                AppZLGroupBean fzBean = (AppZLGroupBean) object;
                FzAdapter fzAdapter = new FzAdapter(this, fzBean.getData().getList());
                DialogPlus dialog = DialogPlus.newDialog(this)
                        .setAdapter(fzAdapter)
                        .setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                                dialog.dismiss();
                                AppZLGroupBean.DataBean.ListBean listBean = (AppZLGroupBean.DataBean.ListBean) item;
                                if (!TextUtils.isEmpty(listBean.getMc())) {
                                    tvStage.setText(listBean.getMc());
                                }
                                updateFz(kid, listBean.getId() + "");
                            }

                        })
                        .setExpanded(true)
                        .create();
                dialog.show();
        }
    }

    private void updateFz(String kid, String fzid) {
        Map<String, Object> map = new HashMap<>();
        map.put("lid", com.jsmy.marketing.manager.UserManager.getInstance().getId());
        map.put("xsid", kid);
        map.put("fzid", fzid);
        mPresenter.loadData(RetrofitManager.getInstance().updateFz(map), Link.APP_UPDATEFZ);

    }

    private void setCustomerInfo(CustomerBean.DataBean bean) {
        NetWork.setImageGlide(this, bean.getIco(), imgAvatar);
        tvName.setText(bean.getXm());
        tvGroup.setText(bean.getGroupmc());
        tvProduct.setText(bean.getPmmc());
        tvStage.setText(bean.getJd());
        tvPhone.setText(bean.getDh());
        tvEmail.setText(bean.getEmail());
        tvWechat.setText(bean.getWeixin());
        tvTecen.setText(bean.getQq());
        tvTip.setText(bean.getNote());
    }


    private void getzlgrouplist() {

        Map<String, Object> map = new HashMap<>();
        map.put("lid", com.jsmy.marketing.manager.UserManager.getInstance().getId());
        mPresenter.loadData(RetrofitManager.getInstance().getappzlgrouplist(map), Link.APP_ZL_GROUP_LIST);
    }

    private void getkhzlinfo(String kid) {

        Map<String, Object> map = new HashMap<>();
        map.put("lid", com.jsmy.marketing.manager.UserManager.getInstance().getId());
        map.put("kid", kid);
        mPresenter.loadData(RetrofitManager.getInstance().getkhzlinfo(map), Link.APP_KHZL_INFO);
    }

    private void getgtkjlist() {

        Map<String, Object> map = new HashMap<>();
        map.put("lid", com.jsmy.marketing.manager.UserManager.getInstance().getId());
        mPresenter.loadData(RetrofitManager.getInstance().getgtkjlist(map), Link.APP_GTLX);
    }

    private void getgtrzlxlist() {

        Map<String, Object> map = new HashMap<>();
        map.put("lid", com.jsmy.marketing.manager.UserManager.getInstance().getId());
        mPresenter.loadData(RetrofitManager.getInstance().getGTKJList(map), Link.APP_GTKJ_LIST);
    }

    @OnClick({R.id.btn_plane, R.id.btn_daily, R.id.tv_phone, R.id.tv_email, R.id.tv_tecen, R.id.tv_stage})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_plane:
                Bundle b = new Bundle();
                b.putString("name", tvName.getText().toString().trim());
                b.putString("kid", kid);
                openActivityForResult(AddPlantActivity.class, b, 100);
                break;
            case R.id.btn_daily:
                showDailyDialog();
                break;
            case R.id.tv_phone:
                MesssageUtil.call(this, tvPhone.getText().toString().trim());
                break;
            case R.id.tv_email:
                ClipData clipEmail = ClipData.newPlainText("邮箱", tvEmail.getText().toString().trim());
                cm.setPrimaryClip(clipEmail);
                ToastUtil.showShort(this, "邮箱复制成功！");
                break;
            case R.id.tv_tecen:
                ClipData clipQQ = ClipData.newPlainText("QQ", tvTecen.getText().toString().trim());
                cm.setPrimaryClip(clipQQ);
                ToastUtil.showShort(this, "QQ复制成功！");
                break;
            case R.id.tv_stage://更换阶段
                getzlgrouplist();
                break;
            default:
                break;
        }
    }

    String daily = "";
    int currentPosition = 0;

    public void showDailyDialog() {

        final BottomSheetDialog dialog = new BottomSheetDialog(this);
        dialog.setContentView(R.layout.bottom_sheet_daily);
        dialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(android.R.color.transparent);
        final ImageView btnMsg = (ImageView) dialog.findViewById(R.id.btn_msg);
        final EditText edtMsg = (EditText) dialog.findViewById(R.id.edt_msg);
        edtMsg.setText(daily);
        edtMsg.setSelection(daily.length());
        final TextView btnSave = (TextView) dialog.findViewById(R.id.btn_save);
        final RecyclerView mRcycler = (RecyclerView) dialog.findViewById(R.id.m_rcycler);
        DailyDialogAdapter adapter = new DailyDialogAdapter();
        mRcycler.setLayoutManager(new LinearLayoutManager(this));
        mRcycler.setAdapter(adapter);
        adapter.replaceData(mGtrzlxList);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                currentPosition = position;
                edtMsg.setText(mGtrzlxList.get(position).getMc());
            }
        });
        edtMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                daily = s.toString();
            }
        });
        btnMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mRcycler.getVisibility() == View.VISIBLE) {
                    mRcycler.setVisibility(View.GONE);
                    btnMsg.setImageResource(R.drawable.ic_menu_arrowupward);
                } else {
                    mRcycler.setVisibility(View.VISIBLE);
                    btnMsg.setImageResource(R.drawable.ic_menu_arrowdownward);
                }
            }
        });
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!edtMsg.getText().toString().isEmpty())

                    savenewgtrzinfo(kid, edtMsg.getText().toString(), mGtrzlxList.get(currentPosition).getId() + "");
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void savenewgtrzinfo(String kid, String nr, String pgtlx) {
        Map<String, Object> map = new HashMap<>();
        map.put("lid", UserManager.getInstance().getId());
        map.put("kid", kid);
        map.put("nr", nr);
        map.put("pgtlx", pgtlx);
        mPresenter.loadData(RetrofitManager.getInstance().saveNewsRzInfo(map), Link.APP_SAVE_NEW_GTRZ_INFO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 100) {
            customerPlantFragment.update();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_customer, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_commit://编辑
                Bundle b = new Bundle();
                b.putString("kid", kid);
                openActivity(CustomerInfoActivity.class, b);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
